<template>
  <div class="teenagers-wrapper">
    <p class="title">
      综合条件查询
      <el-link class="advance-search-btn" type="primary" :underline="false" @click="toggleAdvance">
        高级搜索<i class="el-icon-caret-bottom el-icon--right"></i>
      </el-link>
    </p>
    <div class="form-search-area">
      <el-form :inline="true" :model="formInline" size="medium" class="demo-form-inline">
        <el-form-item label="姓名">
          <el-input v-model="formInline.personNameLike" placeholder="请输入姓名" clearable></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="formInline.sex" placeholder="请选择性别" clearable>
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="出生日期">
          <el-date-picker
            v-model="formInline.birthDate"
            type="date"
            placeholder="请选择选择出生日期" clearable>
          </el-date-picker>
        </el-form-item>
        <el-form-item label="公民身份号码">
          <el-input v-model="formInline.idCardLike" placeholder="请输入公民身份号码" clearable></el-input>
        </el-form-item>
        <el-form-item label="人员类型">
          <el-select v-model="formInline.youngsterType" placeholder="请选择人员类型" clearable>
            <el-option
              v-for="(item) in DICY.youngsterType"
              :key="item.code"
              :label="item.name"
              :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="现住地">
          <el-input v-model="formInline.currentResidenceLike" placeholder="请输入现住地" clearable></el-input>
        </el-form-item>
        <el-form-item label="籍贯" v-show="advanceStatus">
          <el-input v-model="formInline.nativePlace" placeholder="请输入籍贯" clearable></el-input>
        </el-form-item>
        <el-form-item label="婚姻状况" v-show="advanceStatus">
          <el-select v-model="formInline.maritalStatus" placeholder="请选择婚姻状况" clearable>
            <el-option
              v-for="(item, index) in DICY.maritalStatus"
              :key="index"
              :label="item.name"
              :value="item.name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文化程度" v-show="advanceStatus">
          <el-select v-model="formInline.educationLevel" placeholder="请选择文化程度" clearable>
            <el-option
              v-for="(item) in DICY.educationLevel"
              :key="item.code"
              :label="item.name"
              :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="职业" v-show="advanceStatus">
          <el-input v-model="formInline.profession" placeholder="请输入职业" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="medium" @click="searchOrg">查询</el-button>
          <el-button size="medium" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="right-btn-area">
        <el-button size="medium" type="primary" @click="popNewAddDialog">新增重点青少年</el-button>
        <el-button size="medium">导入</el-button>
        <el-button size="medium">导出</el-button>
        <el-button size="medium" @click="batchDeletion">批量删除</el-button>
        <el-button size="medium">批量关联</el-button>
      </div>
    </div>
    <!-- 表格 开始-->
    <div class="table-area clearfix">
      <el-table :data="tableData" ref="multipleTable" @selection-change="selectionChange" v-loading="loading" stripe>
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="序号" width="50">
          <template slot-scope="scope">{{ scope.$index + 1 }}</template>
        </el-table-column>
        <el-table-column label="姓名" prop="personName"></el-table-column>
        <el-table-column label="性别" prop="sex"></el-table-column>
        <el-table-column label="公民身份号码" prop="idCard"></el-table-column>
        <el-table-column label="联系方式" prop="contact"></el-table-column>
        <el-table-column label="人员类型" prop="youngsterType" min-width="100">
          <template slot-scope="scope">{{convertKeyToVal(scope.row.youngsterType, DICY.youngsterType)}}</template>
        </el-table-column>
        <el-table-column label="所属管辖范围" prop="jurisdiction"></el-table-column>
        <el-table-column label="操作" min-width="110">
          <template slot-scope="scope">
            <el-link type="primary" :underline="false" icon="el-icon-view" @click="viewDetail(scope.row.id)">查看</el-link>
            <el-link type="success" :underline="false" icon="el-icon-edit" @click="editDetail(scope.row.id)">编辑</el-link>
            <el-link type="danger" :underline="false" icon="el-icon-delete" @click="deleteDetail(scope.row.id)">删除</el-link>
            <el-link type="warning" :underline="false" icon="el-icon-attract">关联</el-link>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="paging-self"
        background
        :current-page.sync="currentPage"
        @current-change="pageChange"
        layout="total, prev, pager, next"
        :total="totalCount">
      </el-pagination>
    </div>
    <!-- 表格 结束-->
    <!-- 对话框 开始 -->
    <el-dialog title="重点青少年" :visible.sync="dialogFormVisible" width="1140px" @closed="closeDialog">
      <el-form :model="dialogForm" class="dialog-form-comot" :disabled="dialogMode===CNST.READ_MODE" :rules="rules" ref="ruleDialog">

        <el-row>
          <el-col :span="12" v-for="(field, index) in allFields" :key="index">
            <el-form-item :label="field.fieldTxt" label-width="162px" :prop="field.fieldName">
              <el-input v-if="field.UiType===1" v-model="dialogForm[field.fieldName]" :placeholder="field.placeholder" autocomplete="off" clearable></el-input>
              <el-input v-if="field.UiType===4" v-model="dialogForm[field.fieldName]" :placeholder="field.placeholder" autocomplete="off" clearable type="textarea"></el-input>
              <el-select
               v-if="field.UiType===2||field.UiType===21"
               v-model="dialogForm[field.fieldName]"
               :placeholder="field.placeholder"
               clearable
               :multiple="field.UiType===21"
               :disabled="field.fieldName==='populationType'">
                <el-option
                  v-for="(item) in optionsList(field.fieldName)"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code">
                </el-option>
              </el-select>
              <el-date-picker v-if="field.UiType===3"
                v-model="dialogForm[field.fieldName]"
                type="date"
                :placeholder="field.placeholder"
                clearable>
              </el-date-picker>
              <el-date-picker v-if="field.UiType===31"
                v-model="dialogForm[field.fieldName]"
                type="daterange"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitOrg" v-if="dialogMode!==CNST.READ_MODE">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 对话框 结束 -->
  </div>
</template>

<script>
import allFields from '../youthFields'
import { mapState } from 'vuex'
import {
  getPopulationSpecialList,
  getPopulationSpecialDetail,
  addPopulationSpecial,
  updatePopulationSpecialDetail,
  deletePopulationSpecial,
  deletePopulationSpecialBatch
} from '@/api/baseBusiness'
import { deepClone, convertDateToString } from '@/utils'

let currentPopulationType = '6'

export default {
  name: 'Teenagers',
  data () {
    return {
      allFields,
      advanceStatus: false,
      formInline: {
        personNameLike: '',
        sex: '',
        birthDate: '',
        idCardLike: '',
        youngsterType: '',
        currentResidenceLike: '',
        nativePlace: '',
        maritalStatus: '',
        educationLevel: '',
        profession: ''
      },
      loading: false,
      tableData: [],
      multipleSelection: [],
      currentPage: 1,
      totalCount: 0,
      dialogFormVisible: false,
      dialogForm: {
      },
      rules: {
      },
      dialogMode: '', // 对话框的状态，新增，查看，编辑
      curId: '', // 点击查看或编辑的当前列表项的id
      options: this.DICY.jilian
    }
  },
  computed: {
    ...mapState([
      'areaId'
    ]),
    ruleFields () {
      return this.allFields.filter(obj => obj.must)
    }
  },
  methods: {
    initDialogForm (arr = []) {
      arr.forEach((obj) => {
        this.$set(this.dialogForm, obj.fieldName, '')
      })
    },
    initRules () {
      this.ruleFields.forEach((obj) => {
        if (obj.UiType === 1 || obj.UiType === 4) {
          this.$set(this.rules, obj.fieldName, [{ required: true, message: obj.placeholder, trigger: 'blur' }])
        } else {
          this.$set(this.rules, obj.fieldName, [{ required: true, message: obj.placeholder, trigger: 'change' }])
        }
      })
    },
    spanGrid (field) {
      if (field.UiType === 31 || field.UiType === 21) {
        return 12
      }
      if (field.UiType === 4) {
        let span24 = [
          'checkDepositSituation', 'depositCorrectionSituation',
          'checkOmitSituation', 'omitCorrectionSituation',
          'rewardPunishSituation', 'criminalLawChageSituation', 'depositReason', 'helpSituation', 'serviceSpace'
        ]
        if (span24.includes(field.fieldName)) {
          return 24
        }
        return 16
      }
      return 8
    },
    optionsList (fieldName) {
      if (fieldName === 'populationType') {
        return this.DICY.populationTypeSpecial
      } else {
        return this.DICY[fieldName]
      }
    },
    convertKeyToVal (code, arr) {
      arr = Array.isArray(arr) ? arr : []
      let resArr = arr.filter((item) => {
        return item.code === code
      })
      if (resArr.length === 0) {
        return ''
      }
      return resArr[0].name
    },
    toggleAdvance () {
      // this.$refs.advancedForm.classList.toggle('shrink')
      this.advanceStatus = !this.advanceStatus
    },
    searchOrg () {
      this.currentPage = 1
      this.getOrgListAndShow()
    },
    resetSearch () {
      for (let key in this.formInline) {
        this.$set(this.formInline, key, '')
      }
      this.currentPage = 1
      this.getOrgListAndShow()
    },
    popNewAddDialog () {
      this.dialogFormVisible = true
      this.dialogMode = this.CNST.ADDNEW_MODE
    },
    batchDeletion () {
      if (this.multipleSelection.length === 0) {
        this.$message({
          type: 'warning',
          message: '请勾选要删除的项!'
        })
      } else {
        var ids = this.multipleSelection.map((item) => {
          return item.id
        }).join(',')
        this.$confirm('确定删除, 是否继续?', '批量删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deletePopulationSpecialBatch({ ids }).then((res) => {
            this.$message({
              type: 'success',
              message: '批量删除成功!'
            })
            this.getOrgListAndShow()
          })
        })
      }
    },
    selectionChange (valArr) {
      this.multipleSelection = valArr
    },
    showToDialog (data) {
      for (let key in data) {
        if (this.dialogForm.hasOwnProperty(key)) {
          this.$set(this.dialogForm, key, data[key])
        }
      }
    },
    viewDetail (id) {
      this.dialogMode = this.CNST.READ_MODE
      this.dialogFormVisible = true
      getPopulationSpecialDetail({ id }).then((res) => {
        this.showToDialog(res.data)
      })
    },
    editDetail (id) {
      this.dialogMode = this.CNST.EDIT_MODE
      this.dialogFormVisible = true
      this.curId = id
      getPopulationSpecialDetail({ id }).then((res) => {
        this.showToDialog(res.data)
      })
    },
    deleteDetail (id) {
      this.$confirm('确定删除, 是否继续?', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then((res) => {
        deletePopulationSpecial({ id }).then((res) => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getOrgListAndShow()
        })
      })
    },
    pageChange (curPage) {
      this.currentPage = curPage
      this.getOrgListAndShow()
    },
    submitOrg () {
      this.$refs.ruleDialog.validate((valid) => {
        if (valid) {
          // -----------------
          let requestData = deepClone(this.dialogForm)
          convertDateToString(requestData)
          requestData.populationType = currentPopulationType
          if (this.dialogMode === this.CNST.ADDNEW_MODE) {
            // 新增
            requestData.areaId = this.areaId
            addPopulationSpecial(requestData).then((res) => {
              this.$message({
                message: '新增成功',
                type: 'success'
              })
              this.getOrgListAndShow()
              this.dialogFormVisible = false
            })
          } else if (this.dialogMode === this.CNST.EDIT_MODE) {
            // 修改
            requestData.id = this.curId
            updatePopulationSpecialDetail(requestData).then((res) => {
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              this.getOrgListAndShow()
              this.dialogFormVisible = false
            })
          }
          // -----------------
        } else {
          return false
        }
      })
    },
    async getOrgListAndShow () {
      try {
        this.loading = true
        let requestData = {
          page: this.currentPage,
          areaId: this.areaId,
          ...deepClone(this.formInline)
        }
        convertDateToString(requestData)
        var res = await getPopulationSpecialList(requestData)
        this.tableData = res.data.queryResult.filter(item => item.populationType === currentPopulationType)
        this.totalCount = res.data.totalCount - res.data.queryResult.filter(item => item.populationType !== currentPopulationType).length
      } catch (error) {
        console.error(error)
      } finally {
        this.loading = false
      }
    },
    closeDialog () {
      // 当前点击查看或编辑列表项的id置空
      this.curId = ''
      // 弹框关闭后重置表单验证
      this.$refs.ruleDialog.resetFields()
      // 清空弹框内表单数据
      for (let key in this.dialogForm) {
        this.dialogForm[key] = ''
      }
    },
    handleChange (value) {
      console.log(value)
    }
  },
  created () {
    this.initDialogForm(allFields)
    this.initRules()
  },
  mounted () {
    this.getOrgListAndShow()
  }
}
</script>

<style lang="scss" scoped>
.teenagers-wrapper {
  background-color: #ffffff;
  margin-top: 20px;
  border-radius: 4px;
  box-shadow: 10px 10px 22px -2px #d2d6da;
  padding: 20px;
  .title {
    margin: 0;
    font-size: 15px;
    color: #333333;
    margin-bottom: 10px;
    .advance-search-btn {
      float: right;
      user-select: none;
    }
  }
  .form-search-area {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    .advanced-form-box {
      overflow: hidden;
      transition: all 200ms;
      &.shrink {
        display: inline-block;
        width: 0;
        height: 0;
        transition: all 200ms;
      }
    }
    .right-btn-area {
      height: 58px;
    }
  }
  .table-area {
    .el-link {
      margin-right: 13px;
    }
    .el-pagination.paging-self {
      margin-top: 20px;
      float: right;
    }
  }
  .el-form.dialog-form-comot {
    .el-form-item {
      .el-cascader,.el-select,.el-input-number {
        width: 100%;
      }
      .el-date-editor--daterange.el-input__inner {
        width: 100%;
      }
      .el-date-editor.el-input,.el-date-editor.el-input__inner {
        width: 100%;
      }
    }
  }
}
</style>
